package com.vcc.service.impl;

import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.vcc.core.exception.NotFoundException;
import com.vcc.data.entity.Rate;
import com.vcc.data.mapper.RateMapper;
import com.vcc.service.boss.request.rate.CreateRateDto;
import com.vcc.service.boss.request.rate.UpdateRateDto;
import com.vcc.service.service.RateService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RateServiceImpl extends ServiceImpl<RateMapper, Rate> implements RateService {

    @Override
    public Rate getById(Long id) {
        return queryChain().eq(Rate::getId,id).oneOpt().orElseThrow(()-> new NotFoundException("没有当前费率"));
    }

    @Override
    public Boolean existsById(Long id) {
        return queryChain().eq(Rate::getId,id).exists();
    }

    @Override
    public Rate createRate(CreateRateDto createRateDto) {
        //取消原定的初始汇率
        if(createRateDto.getInitFlag().equals(0)){
            if (queryChain().eq(Rate::getInitFlag,0).exists()) {
                updateChain().set(Rate::getInitFlag,1).eq(Rate::getInitFlag,0).update();
            }
        }
        Rate rate = new Rate();
        rate.setRate(createRateDto.getRate());
        rate.setName(createRateDto.getName());
        rate.setScene(createRateDto.getScene());
        rate.setInitFlag(createRateDto.getInitFlag());
        save(rate);
        return rate;
    }

    @Override
    public Boolean updateRate(UpdateRateDto updateRateDto) {
        Rate rate = getById(updateRateDto.getId());
        //取消原定的初始汇率
        if(updateRateDto.getInitFlag().equals(0) && !rate.getInitFlag().equals(0)){
            if (queryChain().eq(Rate::getInitFlag,0).exists()) {
                updateChain().set(Rate::getInitFlag,1).eq(Rate::getInitFlag,0).update();
            }
        }
        updateChain().eq(Rate::getId,rate.getId()).set(Rate::getRate,updateRateDto.getRate()).set(Rate::getInitFlag,updateRateDto.getInitFlag()).update();
        return true;
    }

    @Override
    public Rate getByIdForNull(Long id) {
        return queryChain().eq(Rate::getId,id).oneOpt().orElse(null);
    }

    @Override
    public List<Rate> listByScene(String scene) {
        return queryChain().eq(Rate::getScene,scene).list();
    }

}
